package com.common.sdk.net.connect.http.center;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SohuImageView extends ImageView {

    private static final int NULL_BITMAP = 0;
    private static final int FADE_IN_TIME = 200;

    // 当前ImageView显示图片的hashcode,用于避免重复加载
    private int mCurrentImageCode = NULL_BITMAP;

    public SohuImageView(Context context) {
        super(context);
    }

    public SohuImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SohuImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 显示图片
     * 
     * @param bm
     */
    public void setDisplayImage(Bitmap bm) {
        if (bm != null) {
            int hashCode = bm.hashCode();
            if (mCurrentImageCode != hashCode) {
                // 避免重复加载
                setImageBitmap(bm);
            }
        }
    }

    /**
     * 显示图片,带动画
     * 
     * @param bm
     */
    public void setDisplayImageInAnimation(Bitmap bitmap) {
        if (bitmap != null) {
            int hashCode = bitmap.hashCode();
            if (mCurrentImageCode != hashCode) {
                // Transition drawable with a transparent drwabale and the
                // final
                // bitmap
                TransitionDrawable td = new TransitionDrawable(new Drawable[] {
                        new ColorDrawable(android.R.color.transparent), new BitmapDrawable(getResources(), bitmap) });
                final WeakReference<TransitionDrawable> tdReference = new WeakReference<TransitionDrawable>(td);
                td = null;
                TransitionDrawable transDraw = tdReference.get();
                if (null != transDraw) {
                    setImageDrawable(tdReference.get());
                    transDraw.startTransition(FADE_IN_TIME);
                } else {
                    setImageBitmap(bitmap);
                }
            }
        }
    }

}
